package com.zzzzzz.config;

import org.apache.shiro.authc.credential.DefaultPasswordService;
import org.apache.shiro.authc.credential.PasswordMatcher;
import org.apache.shiro.cache.ehcache.EhCacheManager;
import org.apache.shiro.crypto.hash.DefaultHashService;
import org.apache.shiro.realm.Realm;
import org.apache.shiro.spring.LifecycleBeanPostProcessor;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.zzzzzz.account.signin.ShiroDbRealm;

@Configuration
public class SecurityConfig {
	
	@Bean(name = "passwordService")
	public DefaultPasswordService configPasswordService() {
		DefaultPasswordService passwordService = new DefaultPasswordService();
		DefaultHashService hashService = new DefaultHashService();
        hashService.setHashAlgorithmName("SHA-512");
        hashService.setHashIterations(1024);
        hashService.setGeneratePublicSalt(true);
        passwordService.setHashService(hashService);
		return passwordService;
	}
	
	@Bean(name = "passwordMatcher")
	public PasswordMatcher configPasswordMatcher(){
		PasswordMatcher passwordMatcher = new PasswordMatcher();
		passwordMatcher.setPasswordService(configPasswordService());
		return passwordMatcher;
	}
	
	@Bean
	public Realm configureRealm() {
		return new ShiroDbRealm();
	}
	
	@Bean(name = "securityManager")
	public DefaultWebSecurityManager configSecurityManager() {
		DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
		securityManager.setRealm(configureRealm());
//		securityManager.setCacheManager(configEhCacheManager());
		return securityManager;
	}
	
	/*private EhCacheManager configEhCacheManager() {
		EhCacheManager ehCacheManager = new EhCacheManager();
		ehCacheManager.setCacheManagerConfigFile("classpath:ehcache/ehcache-shiro.xml");
		return ehCacheManager;
	}*/
	
	
	@Bean(name = "shiroFilter")
	public ShiroFilterFactoryBean configShiroFilterFactoryBean() {
		ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
		shiroFilterFactoryBean.setSecurityManager(configSecurityManager());
		shiroFilterFactoryBean.setLoginUrl("/login");
		shiroFilterFactoryBean.setUnauthorizedUrl("/unauthorized");
		shiroFilterFactoryBean.setFilterChainDefinitions("/login = authc");
		return shiroFilterFactoryBean;
	}
	
	@Bean(name = "lifecycleBeanPostProcessor")
	public LifecycleBeanPostProcessor configLifecycleBeanPostProcessor() {
		LifecycleBeanPostProcessor lifecycleBeanPostProcessor = new LifecycleBeanPostProcessor();
		return lifecycleBeanPostProcessor;
	}
}
